<div class="stats-container">
  <div class="header-card">
    <div class="filter-section">
      <div class="library-filter">
        <div class="select-row">
          <label for="library-dropdown">Library Statistics</label>
          <div class="flex w-full gap-2 align-items-center">
            <p-select
              fluid
              id="library-dropdown"
              [options]="libraryOptions"
              [(ngModel)]="selectedLibrary"
              optionLabel="name"
              size="small"
              placeholder="Select a library"
              (onChange)="onLibraryChange()"
              appendTo="body"
              [style]="{'min-width': '200px'}"
              class="library-dropdown">
            </p-select>

            <p-button
              outlined
              size="small"
              (onClick)="toggleConfigPanel()"
              icon="pi pi-cog">
            </p-button>
          </div>
        </div>

        <div class="library-totals" role="status" aria-live="polite">
          <div class="total-item total-books" title="Total books">
            <i class="pi pi-book"></i>
            <span class="total-label">Books</span>
            <span class="total-value">{{ totalBooks$ | async }}</span>
          </div>

          <div class="total-item total-authors" title="Total authors">
            <i class="pi pi-users"></i>
            <span class="total-label">Authors</span>
            <span class="total-value">{{ totalAuthors$ | async }}</span>
          </div>

          <div class="total-item total-series" title="Total series">
            <i class="pi pi-bookmark"></i>
            <span class="total-label">Series</span>
            <span class="total-value">{{ totalSeries$ | async }}</span>
          </div>

          <div class="total-item total-publishers" title="Total publishers">
            <i class="pi pi-building"></i>
            <span class="total-label">Publishers</span>
            <span class="total-value">{{ totalPublishers$ | async }}</span>
          </div>

          <div class="total-item total-size" title="Total size">
            <i class="pi pi-file"></i>
            <span class="total-label">Library Size</span>
            <span class="total-value">{{ totalSize$ | async }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Chart Configuration Modal Overlay -->
  @if (showConfigPanel) {
    <div class="config-modal-overlay" (click)="closeConfigPanel()">
      <div class="config-modal" (click)="$event.stopPropagation()">
        <div class="config-modal-header">
          <h3><i class="pi pi-cog"></i> Chart Configuration</h3>
          <button type="button" class="close-btn" (click)="closeConfigPanel()" title="Close">
            <i class="pi pi-times"></i>
          </button>
        </div>

        <div class="config-modal-actions">
          <button type="button" class="config-action-btn enable-all" (click)="enableAllCharts()">
            <i class="pi pi-check"></i> Enable All
          </button>
          <button type="button" class="config-action-btn disable-all" (click)="disableAllCharts()">
            <i class="pi pi-times"></i> Disable All
          </button>
          <button type="button" class="config-action-btn reset-order" (click)="resetChartOrder()">
            <i class="pi pi-refresh"></i> Reset Order
          </button>
          <button type="button" class="config-action-btn reset-positions" (click)="resetChartPositions()">
            <i class="pi pi-map"></i> Reset Positions
          </button>
        </div>

        <div class="config-modal-content">
          <div class="config-categories">
            <div class="config-category">
              <h4>Small Charts</h4>
              <div class="chart-toggles">
                @for (chart of getChartsByCategory('small'); track chart.id) {
                  <div class="chart-toggle">
                    <input
                      type="checkbox"
                      [id]="'chart-' + chart.id"
                      [checked]="chart.enabled"
                      (change)="toggleChart(chart.id)">
                    <label [for]="'chart-' + chart.id">{{ chart.name }}</label>
                  </div>
                }
              </div>
            </div>

            <div class="config-category">
              <h4>Medium Charts</h4>
              <div class="chart-toggles">
                @for (chart of getChartsByCategory('medium'); track chart.id) {
                  <div class="chart-toggle">
                    <input
                      type="checkbox"
                      [id]="'chart-' + chart.id"
                      [checked]="chart.enabled"
                      (change)="toggleChart(chart.id)">
                    <label [for]="'chart-' + chart.id">{{ chart.name }}</label>
                  </div>
                }
              </div>
            </div>

            <div class="config-category">
              <h4>Large Charts</h4>
              <div class="chart-toggles">
                @for (chart of getChartsByCategory('large'); track chart.id) {
                  <div class="chart-toggle">
                    <input
                      type="checkbox"
                      [id]="'chart-' + chart.id"
                      [checked]="chart.enabled"
                      (change)="toggleChart(chart.id)">
                    <label [for]="'chart-' + chart.id">{{ chart.name }}</label>
                  </div>
                }
              </div>
            </div>

            <div class="config-category">
              <h4>Full Width Charts</h4>
              <div class="chart-toggles">
                @for (chart of getChartsByCategory('full-width'); track chart.id) {
                  <div class="chart-toggle">
                    <input
                      type="checkbox"
                      [id]="'chart-' + chart.id"
                      [checked]="chart.enabled"
                      (change)="toggleChart(chart.id)">
                    <label [for]="'chart-' + chart.id">{{ chart.name }}</label>
                  </div>
                }
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  }

  @if (!isLoading && hasData) {
    <div class="charts-grid"
         cdkDropList
         (cdkDropListDropped)="onChartReorder($event)"
         [cdkDropListData]="getEnabledChartsSorted()">

      @for (chartConfig of getEnabledChartsSorted(); track chartConfig.id) {
        <div class="chart-container"
             cdkDrag
             [cdkDragData]="chartConfig"
             [class]="'chart-section ' + chartConfig.category">

          <div class="drag-handle" cdkDragHandle title="Drag to reorder">
            <i class="pi pi-bars"></i>
          </div>

          @switch (chartConfig.id) {
            @case ('readingStatus') {
              <h3>Reading Status</h3>
              <div class="chart-wrapper status-chart">
                <canvas baseChart
                        [data]="(readStatusChartService.statusChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readStatusChartService.statusChartOptions"
                        [type]="readStatusChartService.statusChartType">
                </canvas>
              </div>
            }
            @case ('bookFormats') {
              <h3>Book Formats</h3>
              <div class="chart-wrapper book-type-chart">
                <canvas baseChart
                        [data]="(bookTypeChartService.bookTypeChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="bookTypeChartService.bookTypeChartOptions"
                        [type]="bookTypeChartService.bookTypeChartType">
                </canvas>
              </div>
            }
            @case ('languageDistribution') {
              <h3>Language Distribution</h3>
              <div class="chart-wrapper language-chart">
                <canvas baseChart
                        [data]="(languageDistributionChartService.languageChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="languageDistributionChartService.languageChartOptions"
                        [type]="languageDistributionChartService.languageChartType">
                </canvas>
              </div>
            }
            @case ('bookMetadataScore') {
              <h3>Book Metadata Score</h3>
              <div class="chart-wrapper quality-chart">
                <canvas baseChart
                        [data]="(bookQualityScoreChartService.qualityChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="bookQualityScoreChartService.qualityChartOptions"
                        [type]="bookQualityScoreChartService.qualityChartType">
                </canvas>
              </div>
            }
            @case ('topAuthors') {
              <h3>Top 25 Authors (with Reading Breakdown)</h3>
              <div class="chart-wrapper author-chart">
                <canvas baseChart
                        [data]="(authorPopularityChartService.authorChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="authorPopularityChartService.authorChartOptions"
                        [type]="authorPopularityChartService.authorChartType">
                </canvas>
              </div>
            }
            @case ('topCategories') {
              <h3>Top 25 Categories (with Reading Breakdown)</h3>
              <div class="chart-wrapper completion-chart">
                <canvas baseChart
                        [data]="(readingCompletionChartService.completionChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readingCompletionChartService.completionChartOptions"
                        [type]="readingCompletionChartService.completionChartType">
                </canvas>
              </div>
            }
            @case ('topBooksBySize') {
              <h3>Top 20 Largest Books by File Size</h3>
              <div class="chart-wrapper book-size-chart">
                <canvas baseChart
                        [data]="(bookSizeChartService.bookSizeChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="bookSizeChartService.bookSizeChartOptions"
                        [type]="bookSizeChartService.bookSizeChartType">
                </canvas>
              </div>
            }
            @case ('monthlyReadingPatterns') {
              <h3>Monthly Reading Patterns</h3>
              <div class="chart-wrapper monthly-patterns-chart">
                <canvas baseChart
                        [data]="(monthlyReadingPatternsChartService.monthlyPatternsChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="monthlyReadingPatternsChartService.monthlyPatternsChartOptions"
                        [type]="monthlyReadingPatternsChartService.monthlyPatternsChartType">
                </canvas>
              </div>
            }
            @case ('readingProgress') {
              <h3>Reading Progress</h3>
              <div class="chart-wrapper progress-chart">
                <canvas baseChart
                        [data]="(readingProgressChartService.progressChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readingProgressChartService.progressChartOptions"
                        [type]="readingProgressChartService.progressChartType">
                </canvas>
              </div>
            }
            @case ('externalRating') {
              <h3>External Rating Distribution</h3>
              <div class="chart-wrapper rating-chart">
                <canvas baseChart
                        [data]="(bookRatingChartService.ratingChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="bookRatingChartService.ratingChartOptions"
                        [type]="bookRatingChartService.ratingChartType">
                </canvas>
              </div>
            }
            @case ('personalRating') {
              <h3>Personal Rating Distribution</h3>
              <div class="chart-wrapper personal-rating-chart">
                <canvas baseChart
                        [data]="(personalRatingChartService.personalRatingChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="personalRatingChartService.personalRatingChartOptions"
                        [type]="personalRatingChartService.personalRatingChartType">
                </canvas>
              </div>
            }
            @case ('pageCount') {
              <h3>Page Count Distribution</h3>
              <div class="chart-wrapper page-count-chart">
                <canvas baseChart
                        [data]="(pageCountChartService.pageCountChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="pageCountChartService.pageCountChartOptions"
                        [type]="pageCountChartService.pageCountChartType">
                </canvas>
              </div>
            }
            @case ('readingVelocityTimeline') {
              <h3>Reading Velocity Timeline</h3>
              <div class="chart-wrapper velocity-timeline-chart">
                <canvas baseChart
                        [data]="(readingVelocityTimelineChartService.velocityTimelineChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readingVelocityTimelineChartService.velocityTimelineChartOptions"
                        [type]="readingVelocityTimelineChartService.velocityTimelineChartType">
                </canvas>
              </div>
            }
            @case ('topSeries') {
              <h3>Top 20 Series by Book Count</h3>
              <div class="chart-wrapper top-series-chart">
                <canvas baseChart
                        [data]="(topSeriesChartService.seriesChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="topSeriesChartService.seriesChartOptions"
                        [type]="topSeriesChartService.seriesChartType">
                </canvas>
              </div>
            }
            @case ('publicationYear') {
              <h3>Publication Year Timeline</h3>
              <div class="chart-wrapper year-chart">
                <canvas baseChart
                        [data]="(publicationYearChartService.yearChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="publicationYearChartService.yearChartOptions"
                        [type]="publicationYearChartService.yearChartType"
                        [plugins]="[ChartDataLabels]">
                </canvas>
              </div>
            }
            @case ('readingDNA') {
              <h3>Your Reading DNA Profile</h3>
              <div class="chart-description">
                Discover your unique reading personality based on behavioral patterns and preferences
              </div>
              <div class="chart-wrapper reading-dna-chart">
                <canvas baseChart
                        [data]="(readingDNAChartService.readingDNAChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readingDNAChartService.readingDNAChartOptions"
                        [type]="readingDNAChartService.readingDNAChartType">
                </canvas>
              </div>
              <div class="dna-insights">
                @if ((readingDNAChartService.readingDNAChartData$ | async)?.datasets?.[0]?.data?.length) {
                  <div class="insights-grid">
                    @for (insight of readingDNAChartService.getPersonalityInsights(); track trackByTrait($index, insight)) {
                      <div class="insight-card">
                        <div class="insight-header">
                          <div class="trait-dot" [style.background-color]="insight.color"></div>
                          <span class="trait-name">{{ insight.trait }}</span>
                          <span class="trait-score">{{ insight.score.toFixed(0) }}%</span>
                        </div>
                        <div class="insight-bar">
                          <div class="insight-fill" [style.width.%]="insight.score" [style.background-color]="insight.color"></div>
                        </div>
                        <p class="insight-description">{{ insight.description }}</p>
                      </div>
                    }
                  </div>
                }
              </div>
            }
            @case ('readingHabits') {
              <h3>Reading Habits Analysis</h3>
              <div class="chart-description">
                Analyze your behavioral reading patterns, routines, and systematic approaches
              </div>
              <div class="chart-wrapper reading-habits-chart">
                <canvas baseChart
                        [data]="(readingHabitsChartService.readingHabitsChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readingHabitsChartService.readingHabitsChartOptions"
                        [type]="readingHabitsChartService.readingHabitsChartType">
                </canvas>
              </div>
              <div class="dna-insights">
                @if ((readingHabitsChartService.readingHabitsChartData$ | async)?.datasets?.[0]?.data?.length) {
                  <div class="insights-grid">
                    @for (habit of readingHabitsChartService.getHabitInsights(); track trackByHabit($index, habit)) {
                      <div class="insight-card">
                        <div class="insight-header">
                          <div class="trait-dot" [style.background-color]="habit.color"></div>
                          <span class="trait-name">{{ habit.habit }}</span>
                          <span class="trait-score">{{ habit.score.toFixed(0) }}%</span>
                        </div>
                        <div class="insight-bar">
                          <div class="insight-fill" [style.width.%]="habit.score" [style.background-color]="habit.color"></div>
                        </div>
                        <p class="insight-description">{{ habit.description }}</p>
                      </div>
                    }
                  </div>
                }
              </div>
            }
            @case ('readingHeatmap') {
              <h3>Books Finished per Month</h3>
              <div class="chart-wrapper reading-heatmap-chart">
                <canvas baseChart
                        [data]="(readingHeatmapChartService.heatmapChartData$ | async) ?? {labels: [], datasets: []}"
                        [options]="readingHeatmapChartService.heatmapChartOptions"
                        [type]="readingHeatmapChartService.heatmapChartType">
                </canvas>
              </div>
            }
          }
        </div>
      }
    </div>
  }

  @if (isLoading) {
    <div class="loading-message">
      Loading statistics...
    </div>
  }

  @if (!isLoading && !hasData) {
    <div class="no-data-message">
      No data available.
      <small>Make sure your library contains books with metadata.</small>
    </div>
  }
</div>
